#include "SeqList.h"

//增删查改等接口函数
void SeqListInit(SL* ps)// 顺序表初始化
{
	ps->a = NULL;
	ps->size = 0;
	ps->capacity = 0;
}

void SeqListCheckCapacity(SL* ps)
{
	// 满了要扩容
	if (ps->size == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		SQDataType* tmp = (SQDataType*)realloc(ps->a, newcapacity * 2 * sizeof(SQDataType));
		if (tmp == NULL)
		{
			printf("realoc fail！");
			exit(-1);
		}
		else
		{
			ps->a = tmp;
			ps->capacity = newcapacity;
		}
	}
}

void SeqListPushBack(SL* ps, SQDataType x)// 尾插
{
	SeqListCheckCapacity(ps);

	ps->a[ps->size] = x;
	ps->size++;

	////复用：
	//SeqListInsert(ps, ps->size, x);

}

void SeqListPushFront(SL* ps, SQDataType x)// 头插
{
	SeqListCheckCapacity(ps);

	int end = ps->size - 1;
	while (end >= 0)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[0] = x;
	ps->size++;

	////复用：
	//SeqListInsert(ps, 0, x);
}

void SeqListPopBack(SL* ps)// 尾删
{
	assert(ps->size > 0);

	//ps->a[ps->size - 1] = 0;
	ps->size--;

	//////复用：
	//SeqListErase(ps, ps->size - 1);
}

void SeqListPopFront(SL* ps)// 头删
{
	assert(ps->size > 0);

	int start = 1;
	while (start < ps->size)
	{
		ps->a[start - 1] = ps->a[start];
		start++;
	}
	ps->size--;

	//////复用：
	//SeqListErase(ps, 0);

}

void SeqListPrint(SL* ps)// 打印
{
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}

void SeqListInsert(SL* ps, int pos, SQDataType x)// 在顺序表的随机位置插入元素
{
	assert(pos < ps->size);
	SeqListCheckCapacity(ps);

	int end = ps->size - 1;
	while (end >= pos)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}

	ps->a[pos] = x;
	ps->size++;
}

void SeqListErase(SL* ps, int pos)// 在顺序表的随机位置删除元素
{
	assert(pos < ps->size);
	int start = pos + 1;
	while (start < ps->size)
	{
		ps->a[start - 1] = ps->a[start];
		start++;
	}
	ps->size--;
}

int SeqListFind(SL* ps, SQDataType x)// 查找顺序表中是否某个元素并返回其下标
{
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x)
		{
			return i;
		}
	}
	return -1;
}

void SeqListModity(SL* ps, int pos, SQDataType x)// 修改顺序表中某下标中的元素
{
	assert(pos < ps->size);
	ps->a[pos] = x;
}

void SeqListDestory(SL* ps)// 销毁顺序表
{
	free(ps->a);
	ps->a = NULL;
	ps->size = ps->capacity = 0;
}